<?php
namespace App\Http\Controllers\Admin\Content;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Library\AttachmentTools;
use App\Models\Content\Attachment;
use App\Models\Content\AttachmentGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FilesController extends AdminController
{
    public function data(Request $request)
    {
        $model = $request->get('recycle') ? Attachment::onlyTrashed() : Attachment::query();
        if ($groupId = $request->get('groupId')) {
            $model->where('group_id', (int)$groupId);
        }
        if ($keywords = $request->get('keywords')) {
            $model->where('file_name', 'like', filterStr($keywords).'%');
        }
        if ($storageMode = $request->get('storageMode')) {
            $model->where('storage', $storageMode);
        }
        if ($minDate = $request->get('minDate')) {
            $model->whereDate('created_at', '>=', trim($minDate));
        }
        if ($maxDate = $request->get('maxDate')) {
            $model->whereDate('created_at', '<=', trim($maxDate));
        }
        $list = $model->select(['id', 'file_name', 'path', 'suffix', 'type', 'storage', 'size', 'created_at'])->orderByDesc('id')->paginate($request->get('limit', 10));
        return $this->succeed([
            'total' => $list->total(),
            'rows'  => $list->items(),
        ]);
    }

    public function getAllGroup()
    {
        return $this->succeed(AttachmentGroup::query()->select(['id', 'name'])->orderBy('sort')->get());
    }

    public function download(Request $request)
    {
        $request->validate(['pathToFile' => 'required']);
        if ($pathToFile = $request->get("pathToFile")) {
            return response()->download(AttachmentTools::getDisk(config("custom.upload.storage"))->path($pathToFile));
        }
        return $this->error();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        try {
            DB::transaction(function () use ($ids) {
                Attachment::query()->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->delete();
                $this->createSyslog('附件移入回收站', $ids);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function recover(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        try {
            DB::transaction(function () use ($ids) {
                Attachment::onlyTrashed()->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->restore();
                $this->createSyslog('附件从回收站复原', $ids);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function expurgate(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        $list = Attachment::onlyTrashed()->select(['id', 'path', 'storage'])->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->get();
        abort_if($list->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        try {
            DB::transaction(function () use ($list) {
                foreach ($list as $model) {
                    //删除储存文件
                    AttachmentTools::deleteFile($model->path, $model->storage);
                    $model->forceDelete();
                    $this->createSyslog('附件从回收站删除', $model);
                }
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

}
